package com.aqie.rabbit.service.Impl;

import com.aqie.rabbit.bean.db.Group;
import com.aqie.rabbit.bean.db.GroupMember;
import com.aqie.rabbit.bean.db.User;
import com.aqie.rabbit.repositories.GroupMemberRepository;
import com.aqie.rabbit.service.IGroupMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class GroupMemberServiceImpl implements IGroupMemberService {
    @Autowired
    private GroupMemberRepository groupMemberRepository;

    @Override
    public Set<GroupMember> getMembers(Group group) {
        List<GroupMember> members = groupMemberRepository.findByGroup(group).orElse(null);
        if (members == null || members.size() == 0){
            return null;
        }
        // return members.stream().collect(Collectors.toSet());
        return new HashSet<>(members);
    }

    @Override
    public Set<GroupMember> getMembers(User user) {
        List<GroupMember> members = groupMemberRepository.findByUser(user).orElse(null);
        if (members == null || members.size() == 0){
            return null;
        }
        return new HashSet<>(members);
    }

    @Override
    public GroupMember getMember(User user,String groupId) {
        GroupMember member = groupMemberRepository.findByUserAndGroupId(user, groupId).orElse(null);
        if (member == null){
            return null;
        }
        return member;
    }

    @Override
    @Transactional
    public Set<GroupMember> addMembers(Group group, List<User> insertUsers) {
        Set<GroupMember> members = new HashSet<>();
        for (User user : insertUsers){
            GroupMember member = new GroupMember(user, group);
            members.add(member);
        }
        groupMemberRepository.saveAll(members);
        return members;
    }
}
